<?php
	namespace Api\Controller;
	use Think\Controller;
	header("Content-Type:text/html;charset=utf-8");
	class DemandController extends Controller
	{
		/*
		 *发布需求
		 *
		 */
		public function publishDemand($uid=null, $token=null)
		{
			if ($this->checkedToken($uid, $token)) 
			{
				$condition["uid"] = $uid;
				$Info = M("User") -> field("dtttype,type") -> where($condition) -> find(); 
				
				//var_dump($Info);
				//发布需求的字段
				if ($Info == null)
				{
					$data = array(
							"uid"=>$uid,
							"dmtitle"=>I('post.title'),
							"tagname"=>I('post.tagname'),
							"demandtime"=>I('post.time'),
							"address"=>I('post.address'),
							"dmpeople"=>I('post.dmpeople'),
							"dmsex"=>I('post.dmsex'),
							"spreadid"=>I('post.spreadid'),
							"applystime"=>I('post.applystime'),
							"dmcontent"=>I('post.dmcontent'),
							"dtttype"=>"0",
							"type"=>"0"
					);
				}
				else 
				{
					$data = array(
							"uid"=>$uid,
							"dmtitle"=>I('post.title'),
							"tagname"=>I('post.tagname'),
							"demandtime"=>I('post.time'),
							"address"=>I('post.address'),
							"dmpeople"=>I('post.number'),
							"dmsex"=>I('post.sex'),
							"spreadid"=>I('post.spriceid'),
							"applystime"=>I('post.applystime'),
							"dmcontent"=>I('post.content'),
							"dtttype"=>$Info["dtttype"],
							"type"=>$Info["type"]
					);
					
// 					$data = array(
// 							"uid"=>$uid,
// 							"dmtitle"=>"这是需求标题33",
// 							"tagname"=>"主播",
// 							"demandtime"=>"2016-11-01",
// 							"address"=>"河南省-郑州市",
// 							"dmpeople"=>"4",
// 							"dmsex"=>"0",
// 							"spreadid"=>"3",
// 							"applystime"=>"2016-10-28",
// 							"dmcontent"=>"需求详情,需求地点是在郑州市郑东新区",
// 							"dtttype"=>$Info["dtttype"],
// 							"type"=>$Info["type"]
// 					);
				}
				
				$result = M("Demand") -> data($data) -> add();
				if ($result > 0) 
				{
					$where["uid"] = $uid;
					$dmsentInfo = M("User") -> where($where) -> getField("dmsent");
					if ($dmsentInfo == null) 
					{
						//该用户首次发布需求
						$res = M("User") -> where($where) -> setField("dmsent", $result);
					}
					else
					{
						//用户已发布过需求
						$dmSentArray = explode(",", $dmsentInfo["dmsent"]);
						array_push($dmSentArray, $result);
						$dmsentId = implode(",", $dmSentArray);
						$res = M("User") -> where($where) -> setField("dmsent", $dmsentId);
					}
					
					if ($res > 0) 
					{
						M("User") -> where("uid={$uid}") ->setInc("credit", 10);
						M("Sign") -> where("uid={$uid}") -> setInc("sentdemandtimes", 1);
						$array1['result'] = 0;
						$array1['message'] = "需求发布成功";
						echo json_encode($array1, JSON_UNESCAPED_SLASHES);
						exit;
					}
					else
					{
						$array1['result'] = 10710;
						$array1['message'] = "需求发布失败";
						echo json_encode($array1, JSON_UNESCAPED_SLASHES);
						exit;
					}
				}
				else
				{
					$array1['result'] = 10711;
					$array1['message'] = "需求发布失败";
					echo json_encode($array1, JSON_UNESCAPED_SLASHES);
					exit;
				}
				
			
			}
			else
			{
				$array1['result'] = 10310;
				$array1['message'] = "获取信息失败";
				echo json_encode($array1, JSON_UNESCAPED_SLASHES);
				exit;
			}
			
			
		}
		
		
		/*
		 *已发需求 
		 *   
		 */
		public function sentDemand($uid=null, $token=null)
		{
// 			if ($this->checkedToken($uid,$token)) 
// 			{
				$condition["uid"] = $uid;
				
				$sentInfo = M("User") -> where($condition) -> getField("dmsent");
				//将查询得到的字符串转化为数组
				$sentdmId = explode(",", $sentInfo);
				//var_dump($sentdmId);
				if ($sentInfo != null) 
				{
					$condition1["uid"] = array("in", $sentdmId);
					$sentdmInfo = M("Demand") -> field("dmtitle,address,tagname,address,applypeople,dmtime,applystime") -> where($condition1) -> select();
				
					//var_dump($sentdmInfo);
					foreach ($sentdmInfo as $key=>$value)
					{
						//剩余天数
						if ($value["applystime"] != null) 
						{
							$remainDay = floor((strtotime($value["applystime"])-time())/86400);
							if ($remainDay < 0) 
							{
								$value["remainday"] = "-1";
							}
							else
							{
								//距离报名截止时间剩余的时间
								$value["remainday"] = $remainDay;
							}
						}
						else
						{
							$value["remainday"] = "";
						}
						//发布需求时距离现在的时间
						$value["beforetime"] = $this->wordTime($value["dmtime"]); 
						
						$sentdmInfo[$key] = $value;
					}
				}
				else
				{
					//该用户还未发布过任何需求
					$array1['result'] = 10703;
					$array1['message'] = "该用户还未发布过任何需求";
					echo json_encode($array1, JSON_UNESCAPED_SLASHES);
					exit;
				}
				//var_dump($sentdmInfo);
				
				$array1['result'] = 0;
				$array1['message'] = "查看发布需求成功";
				$array1["sentdmInfo"] = $sentdmInfo;
				echo json_encode($array1, JSON_UNESCAPED_SLASHES);
				exit;
				
// 			}
// 			else
// 	        {
// 	         	$array1['result'] = 10310;
// 	         	$array1['message'] = "获取信息失败";
// 	         	echo json_encode($array1, JSON_UNESCAPED_SLASHES);
// 	         	exit;
// 	        }
		}
		
		/*
		 *已接需求
		 *
		 */
		public function acceptedDemand($uid=null, $token=null)
		{
			if ($this->checkedToken($uid,$token)) 
			{
				
			}
			else
			{
				$array1['result'] = 10310;
				$array1['message'] = "获取信息失败";
				echo json_encode($array1, JSON_UNESCAPED_SLASHES);
				exit;
			}	
		}
		
		/*
		 *需求详情页面
		 *返回json格式
		 */
		public function demandInfo($dmid=null, $uid=null)
		{
			
			if ($dmid != null) 
			{
				//根据需求id获取该需求详情
				$condition["dmid"] = $dmid;
				
				$clicktimes = M("Demand") -> where($condition) -> setInc("clicktimes", 1);
				
				if ($clicktimes > 0) 
				{
					$demandInfo = M("Demand") -> where($condition) -> find();
				}
				
				if ($demandInfo != null) 
				{
					if ($demandInfo["aid"] != null) 
					{
						//该需求是通过后台发布的
					}
					elseif ($demandInfo["uid"] != null)
					{
						//该需求是通过手机端发布的
						$condition1["uid"] = $demandInfo["uid"];
						//发布需求者的信息
						$sentPeople = M("User") ->field("uid,nickname,type,rmtype,dtttype") -> where($condition1) -> find(); 
						
						if ($sentPeople["rmtype"] == 1)
						{
							if ($sentPeople["type"] == 0) 
							{
								//个人发布的需求
								$sentPeopleInfo = M("Userinfo") -> field("tagname,headimg") -> where($condition1) ->find();
								
								if ($sentPeopleInfo != null) 
								{
									//查询得到了发布者的信息
									if ($sentPeopleInfo["tagname"] != null) 
									{
										//发布需求者的标签
										$tagname = explode("-", $sentPeopleInfo["tagname"]);
										unset($sentPeopleInfo["tagname"]);
										$sentPeopleInfo["tagname"] = $tagname;
									}
									else
									{
										$sentPeopleInfo["tagname"] = array();
									}
									//发布需求者的头像
									if ($sentPeopleInfo["headimg"] == null) 
									{
										$sentPeopleInfo["headimg"] = "";
									}
								}
								else
								{
									//未查询到发布者的信息
									$array1['result'] = 10704;
									$array1['message'] = "未查询到发布者的信息";
									echo json_encode($array1, JSON_UNESCAPED_SLASHES);
									exit;
								}	
							}
							else
							{
								//企业发布的需求
								$sentCompanyInfo = M("Company") -> field("tagname,cplogo") -> where($condition1) -> find();
								
								if ($sentCompanyInfo != null)
								{
									if ($sentCompanyInfo["tagname"] != null)
									{
										$tagname = explode("-", $sentCompanyInfo["tagname"]);
										unset($sentCompanyInfo["tagname"]);
										$sentCompanyInfo["tagname"] = $tagname;
									}
									else
									{
										$sentCompanyInfo["tagname"] = array();
									}
									if ($sentCompanyInfo["cplogo"] == null)
									{
										unset($sentCompanyInfo["cplogo"]);
										$sentCompanyInfo["headimg"] = "";
									}
									else
									{
										$cplogoimg = $sentCompanyInfo["cplogo"];
										unset($sentCompanyInfo["cplogo"]);
										$sentCompanyInfo["headimg"] = $cplogoimg;
										
									}
								}
								else
								{
									//未查询到发布企业的信息
									$array1['result'] = 10705;
									$array1['message'] = "未查询到发布企业的信息";
									echo json_encode($array1, JSON_UNESCAPED_SLASHES);
									exit;
								}
							}
							
						}
						
						
					}
					
					if ($demandInfo["spreadid"] == null) 
					{
						$price = "";
					}
					else
					{
						$where["spreadid"] = $demandInfo["spreadid"];
						$price = M("Spread") -> where($where) ->getField("spread");
					}
					
					//需求标签
					if ($demandInfo["tagname"] == null) 
					{
						$dmtagname = array();
					}
					else
					{
						$dmtagname = explode("-", $demandInfo["tagname"]);
						unset($demandInfo["tagname"]);
					}
					
					
					//根据报名截止时间算出距离还剩余多少天
					if ($demandInfo["applystime"] != null)
					{
						$remainDay = floor((strtotime($demandInfo["applystime"])-time())/86400);
						if ($remainDay < 0)
						{
							$demandInfo["remainday"] = "-1";
						}
						else
						{
							//距离报名截止时间剩余的时间
							$demandInfo["remainday"] = $remainDay;
						}
					}
					else
					{
						$demandInfo["remainday"] = "";
					}
					
					if ($demandInfo["dmtime"] != null) 
					{
						//发布距离现在的时间
						$Days = floor((time() - (strtotime($demandInfo["dmtime"])))/86400);
						//var_dump($Days);
						if ($Days < 3)
						{
							//发布时距离现在的时间小于3天需要加new图标
							$icon = "1";
						}
						else
						{
							//发布时距离现在的时间大于3天不需要加new图标
							$icon = "0";
						}
					}
					
					if ($demandInfo["applypeople"] == null) 
					{
						//报名的人
						$number = "0";
						$applyedType = "0";
						$applypeople = array();
					}
					else
					{
						$applypeoples = explode(",", $demandInfo["applypeople"]);
						
						if (in_array($uid, $applypeoples)) 
						{
							//该uid用户已报名
							$applyedType = "1";
						}
						else
						{
							//该uid用户未报名
							$applyedType = "0";
						}
						
						$where1["uid"] = array("in", $applypeoples);
						$userInfo = M("User") -> field("uid,nickname,type,rmtype,dtttype") -> where($where1) ->select();
						
						foreach ($userInfo as $k=>$v)
						{
							if ($v["type"] == 1) 
							{
								unset($v["type"]);
								if ($v["rmtype"] == 1)
								{
									unset($v["rmtype"]);
									$where2["uid"] = $v["uid"];
									$headimg = M("Company") -> field("cplogo") -> where($where2) -> find();
									if ($headimg == null)
									{
										$v["headimg"] = "";
									}
									else
									{
										$v["headimg"] = $headimg["cplogo"];
									}
								}
								else
								{
									$v["headimg"] = "";
								}
							}
							else
							{
								unset($v["type"]);
								if ($v["rmtype"] == 1) 
								{
									unset($v["rmtype"]);
									$where2["uid"] = $v["uid"];
									$headimg = M("Userinfo") -> field("headimg") -> where($where2) -> find();
									if ($headimg == null) 
									{
										$v["headimg"] = "";
									}
									else
									{
										$v["headimg"] = $headimg["headimg"];
									}
								}
								else
								{
									$v["headimg"] = "";
								}
							}
							$userInfo[$k] = $v;
							
						}
						//已报名的人数
						$number = count($applypeoples);
						//已报名人的信息
						$applypeople = $userInfo;
						
					}
					//距离现在的时间前发布
					$demandInfo["beforetime"] = $this->wordTime($demandInfo["dmtime"]);
					
// 					$code = 0;
// 					$message = "获取需求详情成功";
					
					if ($sentPeople["type"] == 0) 
					{
						//艺人发布的需求
						$data = array(
								"headimg"=>$sentPeopleInfo["headimg"],
								"nickname"=>$sentPeople["nickname"],
								"tagname"=>$sentPeopleInfo["tagname"],
								"dmtagname"=>$dmtagname,
								"beforetime"=>$demandInfo["beforetime"],
								"remainday"=>$demandInfo["remainday"],
								"dtttype"=>$demandInfo["dtttype"],
								"applystime"=>$demandInfo["applystime"],
								"title"=>$demandInfo["dmtitle"],
								"dmpeople"=>$demandInfo["dmpeople"],
								"sex"=>$demandInfo["dmsex"],
								"height"=>$demandInfo["dmheight"],
								"address"=>$demandInfo["address"],
								"price"=>$price,
								"content"=>$demandInfo["dmcontent"],
								"number"=>$number,
								"applyed"=>$applypeople,
								"icon"=>$icon,
								"hasapply"=>$applyedType
						);
					}
					else
					{
						//企业发布的需求
						$data = array(
								"headimg"=>$sentCompanyInfo["headimg"],
								"nickname"=>$sentPeople["nickname"],
								"tagname"=>$sentCompanyInfo["tagname"],
								"dmtagname"=>$dmtagname,
								"beforetime"=>$demandInfo["beforetime"],
								"remainday"=>$demandInfo["remainday"],
								"dtttype"=>$userInfo["dtttype"],
								"applystime"=>$demandInfo["applystime"],
								"title"=>$demandInfo["dmtitle"],
								"dmpeople"=>$demandInfo["dmpeople"],
								"sex"=>$demandInfo["dmsex"],
								"height"=>$demandInfo["dmheight"],
								"address"=>$demandInfo["address"],
								"price"=>$price,
								"content"=>$demandInfo["dmcontent"],
								"number"=>$number,
								"applyed"=>$applypeople,
								"icon"=>$icon,
								"hasapply"=>$applyedType
							);
					}
					
// 					var_dump($sentPeopleInfo);
					$array1['result'] = 0;
					$array1['message'] = "获取需求详情成功";
					$array1["demandinfo"] = $data;
					echo json_encode($array1, JSON_UNESCAPED_SLASHES);
					exit;
					
				}
				else
				{
// 					$code = 10707;
// 					$message = "获取需求详情失败";
					
// 					$data = array();
					
					$array1['result'] = 10707;
					$array1['message'] = "获取需求详情失败";
// 					$array1["demandinfo"] = $data;
					echo json_encode($array1, JSON_UNESCAPED_SLASHES);
					exit;
				}
				
			}
			else
			{
// 				$code = 10706;
// 				$message = "获取需求详情失败";
// 				$data = array();
				
				$array1['result'] = 10706;
				$array1['message'] = "获取需求详情失败";
				
				echo json_encode($array1, JSON_UNESCAPED_SLASHES);
				exit;
			}
// 			$this->xml($code, $message, $data);
 		}
 		
 		/*
 		 *需求详情部分
 		 *返回xml格式
 		 */
 		public function demandXml($dmid=null)
 		{
 			$condition["dmid"] = $dmid;
 			$contentInfo = M("Demand") -> where($condition) -> getField("dmcontent");
 			
 			if ($contentInfo == null) 
 			{
 				$code = 10708;
 				$message = "获取需求详情失败";
 				$data = array();
 			}
 			else
 			{
 				$code = 0;
 				$message = "获取需求详情成功";
 				$data = array(
 						"content"=>htmlspecialchars_decode($contentInfo),
 				);
 			}
 			$this->xml($code, $message, $data);
 		}
		
		/* 
		 *返回xml格式 
		 *  
		 */
		protected function xml($code,$message = '',$data = array())
		{
			if(!is_numeric($code))
			{
				return false;
			}
			$result = array(
					'code'=>$code,
					'message'=>$message,
					'data'=>$data
			);
			$xml = '';
			$xml .= "<?xml version='1.0' encoding='UTF-8'?>\n";
			$xml .= "<root>\n";
			$xml .= $this->xmlEncode($result);
			$xml .= "</root>";
			header("Content-Type:text/xml");
			echo $xml;
		}
		protected function xmlEncode($result){
			$xml = $attr ='';
			foreach($result as $key=>$val){
				if(is_numeric($key)){
					$attr = "id='{$key}'";
					$key = "item{$key}";
				}
				$xml .= "<{$key} {$attr}>";
				$xml .= is_array($val) ? self::xmlEncode($val) : $val;
				$xml .= "</{$key}>\n";
			}
			return $xml;
		}
		
		/*
		 *验证token的方法 
		 *   
		 */
		protected function checkedToken($uid = null,$token = null)
		{
			if ($uid==null || $token==null) 
			{
				return false;
			}
			else
			{
				$where["uid"] = $uid;
				$tokeninfo = M("User") -> where($where) -> getField("token");
				if ($token == $tokeninfo) 
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		//求发布需求时距离现在的时间的方法
		protected function wordTime($time) 
		{
			$times = strtotime($time);
			$int = time() - $times;
			$str = '';
			if ($int <= 2){
				$str = sprintf('刚刚', $int);
			}elseif ($int < 60){
				$str = sprintf('%d秒前', $int);
			}elseif ($int < 3600){
				$str = sprintf('%d分钟前', floor($int / 60));
			}elseif ($int < 86400){
				$str = sprintf('%d小时前', floor($int / 3600));
			}elseif ($int < 2592000){
				$str = sprintf('%d天前', floor($int / 86400));
			}else{
				$str = date('Y-m-d H:i:s', $time);
			}
			return $str;
		}
	}